package com.miaosha.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miaosha.entity.Goods;
import com.miaosha.entity.MiaoShaGoods;
import com.miaosha.entity.dto.AuditReqDto;
import com.miaosha.exception.MyException;
import com.miaosha.mapper.GoodsMapper;
import com.miaosha.mapper.MiaoShaGoodsMapper;
import com.miaosha.service.GoodsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


@Service("goodsService")
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {

    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private MiaoShaGoodsMapper miaoShaGoodsMapper;

    @Override
    public Goods findById(Integer id) {
        return goodsMapper.findById(id);
    }

    @Override
    public int update(Goods goods) {
        return goodsMapper.updateById(goods);
    }

    @Override
    public List<Goods> listByName(String name, Long userId) {
        return goodsMapper.listByName(name, userId);
    }

    @Override
    public void removeGood(Long id) throws Exception {
        QueryWrapper<MiaoShaGoods> qw = new QueryWrapper<>();
        qw.eq("goodsId",id);
        if(miaoShaGoodsMapper.selectList(qw).isEmpty()){
            goodsMapper.deleteById(id);
        }else{
            throw new Exception("该商品正在参与秒杀，不可删除");
        }
    }

    @Override
    public void audit(AuditReqDto auditReqDto) {
        Goods good = new Goods();
        good.setId(auditReqDto.getId());
        good.setAuditStatus(auditReqDto.getStatus());
        goodsMapper.updateById(good);
    }
}
